import { getToken,setToken,removeToken } from "@/utils/auth"
import {loginAPI,userInfoAPI,getUserImgAPI} from '@/api/user'
const state = () =>{
    return {
        token:getToken(),
        // 为什么是空对象不是null
        userInfo:{}, 
        isCollapse:false
    }
}
const mutations ={
    setToken(state,token){
        state.token=token
        setToken(token)
    },
    removeToken(state){
        state.token=null
        removeToken()
    },
    // 设置用户信息
    setuserInfo(state,userInfo){
        state.userInfo={...userInfo} //浅拷贝
    },
    // 删除用户信息
    removeuserInfo(state){
        state.userInfo={}
    },
    // 
    Collapse(state){
        state.isCollapse = !state.isCollapse
    }
}

const actions={
    // 登录
    async loginAsync({commit},data){
       let result = await loginAPI(data)
    //    console.log(result);
       commit('setToken',result)
    },
    // 获取用户资料action
    async getuserInfo({commit}){
        const result = await userInfoAPI()
        const basicInfo = await getUserImgAPI(result.userId)
        // 把用户信息和用户头像进行合并
        // console.log(basicInfo,'1111');
        const basicResult = {...result,...basicInfo}
        commit('setuserInfo',basicResult)
        // 目前用不到 后边会用到
        return basicResult
    },
    // 退出
    logout({commit}){
        // 删除token 
        commit('removeToken')
        // 删除用户信息
        commit('removeuserInfo')
    }
}
export default{
    namespaced:true,
    state,
    mutations,
    actions
 }